package com.jinzhi.jzweb.strategy.factory;

import com.jinzhi.jzweb.strategy.BaseStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/*
 *  @author : JingChangTian
 *  @date   : 2023/6/3 14:15
 *  @description :
 *
 */
@Service()
public class PayStrategyFactory {
    private final Map<String, BaseStrategy> strategyMap = new ConcurrentHashMap<>(3);

    private final ApplicationContext applicationContext;

    @Autowired
    public PayStrategyFactory(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    /**
     * 策略模版入口
     */
    @PostConstruct
    public void init() {
        strategyMap.clear();
        Map<String, BaseStrategy> map = applicationContext.getBeansOfType(BaseStrategy.class);
        strategyMap.putAll(map);
    }

    public BaseStrategy get(String model) throws Exception {
        BaseStrategy modelStrategy = strategyMap.get(model);
        if (Objects.isNull(modelStrategy)) {
            throw new Exception("找不到策略处理类！model=" + model);
        }
        return modelStrategy;
    }
}
